package org.example.juc;

public class VolatileReorderDemo {

    public int x = 10;

    public int doubleValue = 0;

    public boolean flag = false;

    public void update(){
        x = 20;
        flag = true;
    }

    public void doubleX() {
        if (flag) {
            doubleValue = x + x;
        }
    }

    public static void main(String[] args) throws Exception{
        int i = 0;
        final VolatileReorderDemo demo = new VolatileReorderDemo();
        for (;;) {
            i++;
            Thread one = new Thread(() -> {
                demo.update();
            });
            Thread two = new Thread(() -> {
                demo.doubleX();
            });
            one.start();
            two.start();
            one.join();
            two.join();
            // 回到主线程
            if (demo.doubleValue == 20) {
                System.out.println("指令重排序doubleValue = " + demo.doubleValue + ", i = " + i);
                break;
            }
        }
    }
}
